package com.turbo.cloud.bpm.web.caches;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.turbo.cloud.bpm.web.entity.CustomFlwGroup;
import com.turbo.cloud.bpm.web.service.ICustomFlwGroupService;
import com.turbo.cloud.core.cache.CaffeineCache;
import com.turbo.cloud.core.annotations.dict.translator.Translator;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 组缓存类
 *
 * @author zhangluning
 */
@Slf4j
@RequiredArgsConstructor
@Component
public class GroupCache extends CaffeineCache implements Translator {
    final ICustomFlwGroupService customFlwGroupService;

    private static final String CACHE_PREFIX = "CacheFlwGroup_";

    /**
     * 查询流程信息分页列表
     *
     * @param id 流程信息ID
     */
    public synchronized CustomFlwGroup getFlwGroupCacheById(String id) {
        String cacheKey = CACHE_PREFIX + id;
        String json = getJson(cacheKey);

        CustomFlwGroup result;
        if (StrUtil.isNotBlank(json)) {
            result = JSON.parseObject(json, CustomFlwGroup.class);
        } else {
            result = customFlwGroupService.getById(id);

            // 缓存5分钟
            setJson(cacheKey, JSON.toJSONString(result), 5, TimeUnit.MINUTES);
        }
        return result;
    }

    @Override
    public String translate(String translationFieldVale) {
        CustomFlwGroup customFlwGroup = getFlwGroupCacheById(translationFieldVale);
        return customFlwGroup.getGroupName();
    }
}
